﻿
@{
    ViewBag.Title = "上传文件";
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<div style="margin:30px;">
    <h2>文件上传</h2>
    <div>
        <input type="file" id="file" style="width:78%;margin:20px 0px;" />
        <input type="button" id="btnDoUpload" value="执行上传" style="width:200px;height:33px; " />
    </div>
    <div id="fileInfo"></div>
    <div>
        <span>上传进度：</span>
        <b id="progressStrip"></b>
    </div>
</div>
<script type="text/javascript">

    var fileMyUploder = {
        //每批次最大发送请求数，设置太大浏览器会报异常net::ERR_INSUFFICIENT_RESOURCES
        concurrentNum: 200,
        //上传成功的计数
        succeed: 0,
        //发送的文件分片下标
        forIndex: 0,
        //总分片数
        shardCount: 0,
        //每批次成功数
        eachIndex: 0,
        //请求id
        requestId: (new Date().getTime() / 1000).toFixed(0),

        uploadUrl: '',//上传后台处理地址
        doneFunc: function () { },//上传成功后回调方法
        sendData: function (i, file, shardSize, size, Count, name) {
            //计算每一片的起始与结束位置
            var start = i * shardSize,
                end = Math.min(size, start + shardSize);
            //构造一个表单，FormData是HTML5新增的
            var index = i + 1;
            var form = new FormData();
            form.append("data", file.slice(start, end));  //slice方法用于切出文件的一部分
            form.append("name", this.requestId +"_"+ name);
            form.append("total", Count);   //总片数
            form.append("index", index);        //当前是第几片
            $("#progressStrip").html(0 + " / " + fileMyUploder.shardCount);
            //Ajax提交
            $.ajax({
                //url: "/Home/Upload?index=" + index,
                url: fileMyUploder.uploadUrl + "?index=" + index,
                type: "POST",
                data: form,
                async: true,         //异步
                processData: false,  //很重要，告诉jquery不要对form进行处理
                contentType: false,  //很重要，指定为false才能形成正确的Content-Type
                success: function (s) {
                    //alert(s);
                    if (s.Code == 1) {
                        //alert("上传失败！");
                        console.log(s.Msg);
                    } else {
                        ++fileMyUploder.succeed;
                        ++fileMyUploder.eachIndex;
                        if (fileMyUploder.eachIndex >= fileMyUploder.concurrentNum && fileMyUploder.succeed <= fileMyUploder.shardCount) {
                            console.log("fileMyUploder.succeed=" + fileMyUploder.succeed);
                            console.log("fileMyUploder.eachIndex=" + fileMyUploder.eachIndex);
                            //剩余数
                            var remainder = Count - fileMyUploder.succeed;
                            console.log("remainder=" + remainder);
                            //console.log("Count=" + Count + ",shardCount=" + fileMyUploder.shardCount);
                            var xhSize = remainder > fileMyUploder.concurrentNum ? fileMyUploder.concurrentNum : remainder;
                            console.log("xhSize=" + xhSize);
                            console.log("forIndex=" + fileMyUploder.forIndex);
                            for (var i = 0; i < xhSize; ++fileMyUploder.forIndex) {
                                fileMyUploder.sendData(fileMyUploder.forIndex, file, shardSize, size, Count, name);
                                i++;
                            }
                            fileMyUploder.eachIndex = 0;
                        }
                    }
                    $("#progressStrip").html(fileMyUploder.succeed + " / " + fileMyUploder.shardCount);
                    if (fileMyUploder.succeed == fileMyUploder.shardCount) {
                        //console.log(s);
                        fileMyUploder.doneFunc(s);//执行上传成功回调
                        fileMyUploder.succeed = 0;
                        fileMyUploder.forIndex = 0;
                        fileMyUploder.shardCount = 0;
                        fileMyUploder.eachIndex = 0;
                        $("#progressStrip").html("完成");
                    }
                },
                error: function (e) {
                    console.log(e);
                    $("#btnDoUpload").removeAttr("disabled");
                    //alert(e);
                    if (e.Code == 1) {
                        //alert("上传失败！");
                    }
                }
            });
        },
        upload: function () {
            fileMyUploder.succeed = 0;
            fileMyUploder.forIndex = 0;
            fileMyUploder.shardCount = 0;
            fileMyUploder.eachIndex = 0;
            var shardSize = 2 * 1024 * 1024;    //以2MB为一个分片

            //如果文件只有1个，并小于50MB,则不分片，直接上传
            if ($("#file")[0].files.length == 1 && $("#file")[0].files[0].size <= 50 * 1024 * 1024) {             
                shardSize = 50 * 1024 * 1024;
                //return;
            }
          
            for (var i = 0; i < $("#file")[0].files.length; i++) {
                fileMyUploder.shardCount += Math.ceil($("#file")[0].files[i].size / shardSize);   //总片数
            }
            for (var j = 0; j < $("#file")[0].files.length; j++) {
                var file = $("#file")[0].files[j],  //文件对象
                    name = file.name,        //文件名
                    size = file.size;        //总大小
                var Count = Math.ceil(file.size / shardSize);
                var xhSize = Count > fileMyUploder.concurrentNum ? fileMyUploder.concurrentNum : Count;
                for (var i = 0; i < xhSize; ++fileMyUploder.forIndex) {
                    fileMyUploder.sendData(fileMyUploder.forIndex, file, shardSize, size, Count, name);
                    i++;
                }
            }
        }
    };


    fileMyUploder.uploadUrl = "/file/DoUpload";//上传后台处理地址
    fileMyUploder.doneFunc = function (d) {
        //上传成功后回调函数
        console.log("上传成功后回调函数:");
        console.log(d);
        $("#btnDoUpload").removeAttr("disabled");

        //var file = $("#file")[0].files[0];//文件对象
        //console.log(file);
        //var fileId = p.uuid();
        //var fileSizeKb = (file.size / 1014).toFixed(1);
        //var htmlArr = ['<tr id="' + fileId + '" fileSizeKb="' + fileSizeKb + '" OriginalFileName="' + file.name + '" durl="' + d.dbFileUrl + '">'
        //    , '<td>' + file.name + '</td>'
        //    , '<td>' + fileSizeKb + 'kb</td>'
        //    , '<td  style="color: #5FB878;">上传成功</td>'
        //    , '<td>'
        //    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
        //    , '</td>'
        //    , '</tr>'];
        //// 如果选的图片则显示出来
        //var imageType = /image.*/;
        //if (file.type.match(imageType)) {
        //    var reader = new FileReader();
        //    reader.onload = function () {
        //        var img = new Image();
        //        img.src = reader.result;
        //        //console.log(img);
        //        //console.log(img.outerHTML);
        //        $("#" + fileId + " td:first").html(img.outerHTML);
        //    };
        //    reader.readAsDataURL(file);
        //}
        //$("#demoList").append(htmlArr.join(''));
        ////删除绑定
        //$(".demo-delete").click(function () {
        //    $(this).parent().parent().remove();
        //});
    }
    $("#btnDoUpload").click(function () {
        $("#btnDoUpload").attr("disabled", "disabled");
        fileMyUploder.upload();
    });
    $("#file").on("change", function () {
        var fileInfo = $("#file")[0].files[0];
        var kb =  parseFloat(fileInfo.size / 1024).toFixed(2) ;
        console.log("文件大小kb=" + kb);
        if (kb < 1024) {
            $("#fileInfo").html("文件大小：" + kb + " KB");
            return;
        }
        var mb =  parseFloat(kb / 1024).toFixed(2) ;
        console.log("文件大小MB=" + mb);
        if (mb < 1024) {
            $("#fileInfo").html("文件大小：" + mb + " MB");
            return;
        }
        var gb =  parseFloat(mb / 1024).toFixed(2) ;
        $("#fileInfo").html("文件大小：" + gb + " GB");
    });

</script>






